package com.xiaoxin.lease.common.minio;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @Author Champions_X
 * @Date 2025/3/25
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {

    @Autowired
    private MinioProperties properties;




    @Bean
    public MinioClient minioClient() throws Exception{
        MinioClient client =  MinioClient.builder()
                .endpoint(properties.getEndpoint())
                .credentials(properties.getAccessKey(), properties.getSecretKey())
                .build();
        boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName())
                        .build());
        if (!bucketExists) {
            client.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(properties.getBucketName())
                            .build());
            String policy = """
                    {
                                   "Statement" : [ {
                                     "Action" : "s3:GetObject",
                                     "Effect" : "Allow",
                                     "Principal" : "*",
                                     "Resource" : "arn:aws:s3:::%s/*"
                                   } ],
                                   "Version" : "2012-10-17"
                                 }
                                 """.formatted(properties.getBucketName());
            client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(policy).build());
        }
        return client;
    }
}
